package com.ggb.reactive.service

import com.ggb.reactive.domain.dto.CategoryPageQueryDTO
import com.ggb.reactive.domain.entity.Category
import com.ggb.reactive.model.PageResult
import com.ggb.reactive.model.WebResult
import lombok.RequiredArgsConstructor
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.PageRequest
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate
import org.springframework.data.relational.core.query.Criteria
import org.springframework.data.relational.core.query.Query
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono

@Service
@RequiredArgsConstructor
class CategoryService(private val r2dbcEntityTemplate: R2dbcEntityTemplate) {

    fun findCategoriesByCriteria(categoryPageQueryDTO: CategoryPageQueryDTO): Mono<WebResult<PageResult<Category>>> {
        var criteria = Criteria.empty()

        categoryPageQueryDTO.name?.let {
            criteria = criteria.and("name").like("%$it%")
        }
        categoryPageQueryDTO.type?.let {
            criteria = criteria.and("type").`is`(it)
        }

        val pageable = PageRequest.of(categoryPageQueryDTO.page - 1, categoryPageQueryDTO.pageSize)


        val query = Query.query(criteria).with(pageable)
        val countQuery = Query.query(criteria)

        return r2dbcEntityTemplate.select(query, Category::class.java).collectList()
            .zipWith(r2dbcEntityTemplate.count(countQuery, Category::class.java))
            .map { tuple -> PageImpl(tuple.t1, pageable, tuple.t2) }
            .map { page ->
                // 将Page<User>转换为你的PageResult<User>（假设你有一个类似的结构）
                WebResult.success(PageResult(total = page.totalElements, records = page.content))
            }
    }

}